package com.yang.test.service.serviceImpl;

import com.yang.test.domain.Category;
import com.yang.test.domain.VO.ResultHVO;
import com.yang.test.domain.QuestionH;
import com.yang.test.domain.TestResult;
import com.yang.test.mapper.HldzyMapper;
import com.yang.test.service.HldzyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class HldzyServiceImpl implements HldzyService {
    
    @Autowired
    private HldzyMapper hldzyMapper;
    
    @Override
    public List<QuestionH> getAllQuestions() {
        return hldzyMapper.selectAllQuestions();
    }

    
    @Override
    public Category getCategoryByKey(String cateKey) {
        return hldzyMapper.selectCategoryByKey(cateKey);
    }
    
    @Override
    public ResultHVO calculateResult(Map<String, Integer> answers) {
        // 计算各类型分数
        Map<String, Integer> scores = new HashMap<>();
        
        // 确保所有类型都有分数，没有回答的默认为0
        scores.put("R", answers.getOrDefault("R", 0));
        scores.put("C", answers.getOrDefault("C", 0));
        scores.put("E", answers.getOrDefault("E", 0));
        scores.put("S", answers.getOrDefault("S", 0));
        scores.put("A", answers.getOrDefault("A", 0));
        scores.put("I", answers.getOrDefault("I", 0));
        
        // 按分数排序并获取前三个类型
        List<Map.Entry<String, Integer>> sortedScores = scores.entrySet()
                .stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .collect(Collectors.toList());
        
        // 构建结果代码（前三类型的组合）
        StringBuilder resultCode = new StringBuilder();
        for (int i = 0; i < Math.min(3, sortedScores.size()); i++) {
            resultCode.append(sortedScores.get(i).getKey());
        }
        
        // 获取主导类型
        String primaryTypeKey = sortedScores.get(0).getKey();
        Category primaryType = getCategoryByKey(primaryTypeKey);
        
        // 构建响应
        ResultHVO response = new ResultHVO();
        response.setResultCode(resultCode.toString());
        response.setScores(scores);
        response.setPrimaryType(primaryType);
        
        // 保存结果到数据库
        TestResult testResult = new TestResult();
        testResult.setResultCode(resultCode.toString());
        testResult.setRScore(scores.get("R"));
        testResult.setCScore(scores.get("C"));
        testResult.setEScore(scores.get("E"));
        testResult.setSScore(scores.get("S"));
        testResult.setAScore(scores.get("A"));
        testResult.setIScore(scores.get("I"));
        
        saveResult(testResult);
        
        return response;
    }
    
    @Override
    public Long saveResult(TestResult testResult) {
        hldzyMapper.insertTestResult(testResult);
        return testResult.getId();
    }
}